package sddz.foodmanage.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.RefreshListenerAdapter;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.lcodecore.tkrefreshlayout.header.progresslayout.ProgressLayout;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.adapter.UniversalAdapter;
import sddz.foodmanage.adapter.UniversalViewHolder;
import sddz.foodmanage.base.BaseActivity;
import sddz.foodmanage.model.CommodityBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.ImageLoader;
import sddz.foodmanage.utils.SpfUtils;

/**
 * @Date:2019/7/5
 * @Author:lbb 搜索商品
 */

public class SearchActivity extends BaseActivity {


    @BindView(R.id.im_back)
    ImageView imBack;
    @BindView(R.id.home_sao_yi_sao)
    AutoLinearLayout homeSaoYiSao;
    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.ll_search)
    AutoLinearLayout llSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.lin_search)
    AutoLinearLayout linSearch;
    @BindView(R.id.shangpinlist)
    ListView shangpinlist;
    @BindView(R.id.news_trl)
    TwinklingRefreshLayout newsTrl;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.activity_search)
    AutoLinearLayout activitySearch;
    private UniversalAdapter adapter;
    private List<CommodityBean.DataBeanX.DataBean> list = new ArrayList<>();
    TextView weight;
    int number;
    ImageView jian;
    ImageView add;
    private int pages = 1;
    CommodityBean commoditybean;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_search);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initData() {
    }

    private void initListener() {
        newsTrl.setOnRefreshListener(new RefreshListenerAdapter() {
            @Override
            public void onRefresh(TwinklingRefreshLayout refreshLayout) {
                super.onRefresh(refreshLayout);
                searchsp(1);
                newsTrl.finishRefreshing();//结束刷新
            }

            @Override
            public void onLoadMore(TwinklingRefreshLayout refreshLayout) {
                super.onLoadMore(refreshLayout);
                if (commoditybean != null) {
                    if (pages < commoditybean.getData().getCurrent_page()) {
                        pages++;
                    }
                }
                searchsp(pages);
                newsTrl.finishLoadmore();//结束加载更多
            }
        });
        shangpinlist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                Intent intent = new Intent(mActivity, NewsDetailActivity.class);
//                intent.putExtra("data", newsList.get(position));
//                startActivity(intent);
            }
        });
    }

    private void initView() {
        imBack.setVisibility(View.VISIBLE);
        ProgressLayout progressLayout = new ProgressLayout(mActivity);
        progressLayout.setColorSchemeResources(R.color.colorPrimary);
        newsTrl.setHeaderView(progressLayout);

        adapter = new UniversalAdapter<CommodityBean.DataBeanX.DataBean>(mActivity, list, R.layout.item_shangpin) {

            @Override
            public void convert(UniversalViewHolder holder, int position, CommodityBean.DataBeanX.DataBean classifyBean) {
                TextView spname = holder.getView(R.id.tv_spname);
                TextView unitprice = holder.getView(R.id.tv_unitprice);
                weight = holder.getView(R.id.tv_weight);
                ImageView imagesp = holder.getView(R.id.image_sp);
                jian = holder.getView(R.id.image_jian);
                add = holder.getView(R.id.image_add);
                weight.setText("0");
                spname.setText(classifyBean.getName());
                unitprice.setText(classifyBean.getPrice() + "元/" + classifyBean.getUnit());
                ImageLoader.loadImageUrl(mActivity, classifyBean.getImgs().get(0).getUrl(), imagesp);

                number = Integer.parseInt(weight.getText().toString());
                jian.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        number = Integer.parseInt(weight.getText().toString());
                        if (number > 0) {
                            number--;
                        } else {

                        }
                    }
                });
                weight.setText(number + "");
                add.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        number = Integer.parseInt(weight.getText().toString());
                        number++;
                        Log.e("点击了加", weight.getText().toString());
                    }
                });
                weight.setText(number + "");

            }
        };
        shangpinlist.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }

    @OnClick({R.id.im_back, R.id.tv_search})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.im_back:
                finish();
                break;
            case R.id.tv_search:
                Log.e("111111", "点击了搜索");
                searchsp(pages);
                break;
        }
    }

    //搜索商品
    private void searchsp(int pages) {
        if (TextUtils.isEmpty(editText.getText().toString())) {
            show("请输入要搜索的商品名称");
            return;
        }
        Map<String, String> params = new HashMap<>();
        params.put("current_page", pages + "");
        params.put("page_size", "10");
        params.put("name", editText.getText().toString());
        params.put("classification_id", "");
        dialog.show();
        Log.e("params", JSON.toJSONString(params));

        HttpUtils.getInstance().POST(mActivity, API.getcommodity, JSON.toJSONString(params), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                dialog.dismiss();
                Log.e("搜索结果：", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (code == 200) {
                            if (list != null) {
                                list.clear();
                            }
                            Log.e("111112222",jsonObject.optString("data"));
                            if (jsonObject.optJSONObject("data")!=null) {
                                commoditybean = new Gson().fromJson(body, CommodityBean.class);
                                if(commoditybean.getData().getData()!=null) {
                                    list.addAll(commoditybean.getData().getData());
                                    Log.e("搜索到的", list.size() + "");
                                    adapter.notifyDataSetChanged();
                                }
                            }

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            searchsp(1);
                        } else if (code == 401) {
                            show(jsonObject.optString("message"));
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
                dialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });

    }


}
